package postgres

import (
	"gitee.com/guolianyu/kit/skit/third_party/config"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// New initialize *gorm.DB
func New(c *config.Database, logger logger.Interface) (*gorm.DB, error) {
	db, err := gorm.Open(postgres.New(postgres.Config{
		DriverName: c.Driver,
		DSN:        c.Source,
	}), &gorm.Config{
		Logger:                                   logger,
		SkipDefaultTransaction:                   true,
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		return nil, err
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}

	if c.MaxIdleConn > 0 {
		sqlDB.SetMaxIdleConns(int(c.MaxIdleConn))
	}

	if c.MaxOpenConn > 0 {
		sqlDB.SetMaxOpenConns(int(c.MaxOpenConn))
	}

	if c.ConnMaxIdleTime.Seconds > 0 {
		sqlDB.SetConnMaxIdleTime(c.ConnMaxIdleTime.AsDuration())
	}

	return db, nil
}
